//
//  shipgdsViewController.m
//  
//
//  Created by turing on 15/11/24.
//
//

#import "shipgdsViewController.h"

#import "ShipperSource_TableViewCell.h"
#import "RouteLine_ViewController.h"
#import "GoodsList_ViewController.h"
#import "shipgdsDetailViewController.h"
#import "DataController.h"
#import "goodsList.h"
#import "MTLJSONAdapter.h"
#import "ChooseVechileViewController.h"
#import "licensePlateList.h"

//#import "UtilsHelper.h"

@interface shipgdsViewController ()

@property(nonatomic ,strong)NSMutableArray *sourceArr;
@property(nonatomic, strong)UITableView *tableView;

@end

@implementation shipgdsViewController
{
    UIView     *_topView;
    UIView     *multipeView;
    UILabel    *pushSourceLabel;
    UIButton   *pushSourceButton;
    UIButton   *shareSourceButton;
    UILabel    *shareSourceLabel;
    UIButton   *_fromButton;
    UIButton   *_toButton;
    UIButton   *_weightButton;
    UIView     *detailView;
    UILabel    *pulicLabel;
    UILabel    *pulicContentLabel;
    
    BOOL       bPush;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.sourceArr = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navtitle.text = @"货源";
    self.leftButton.hidden = YES;
    [self.view setBackgroundColor:[UIColor HexStrWithColor:@"f3f6f5"]];
    
    [self initWithView];

    bPush = true;
    [self verificationLogin];
}

- (void)initWithView;
{
    [self topView];
    [self multipeAreaView];
    [self detailView];
}

/**
 *  顶部按钮
 */
- (void)topView
{
    _topView = [[UIView alloc]initWithFrame:CGRectMake(-1, kStateHeight + kNavHeight, kUIScreenWidth+2, 44)];
    [_topView setBackgroundColor:[UIColor whiteColor]];
    //[_topView setBackgroundColor:[UIColor blackColor]];
    [_topView.layer setBorderColor:[[UIColor HexStrWithColor:@"a9a9a9"] CGColor]];
    [_topView.layer setBorderWidth:1.0];
    [self.view addSubview:_topView];

    pushSourceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [pushSourceButton setFrame:CGRectMake(0, 0, _topView.frame.size.width/2, _topView.frame.size.height)];
    [pushSourceButton setTitle:@"推送货源" forState:UIControlStateNormal];
    [pushSourceButton setSelected:YES];
    [pushSourceButton setTitle:@"推送货源" forState:UIControlStateSelected];
    [pushSourceButton setTitleColor:[UIColor HexStrWithColor:@"ca3300"] forState:UIControlStateSelected];
    [pushSourceButton setTitleColor:[UIColor HexStrWithColor:@"a9a9a9"] forState:UIControlStateNormal];
    [pushSourceButton setTag:1];
    [pushSourceButton addTarget:self action:@selector(ButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [pushSourceButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];

    pushSourceLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, pushSourceButton.frame.size.height-3, pushSourceButton.frame.size.width, 3)];
    [pushSourceLabel setBackgroundColor:[UIColor HexStrWithColor:@"cf3900"]];
    [pushSourceButton addSubview:pushSourceLabel];
    [_topView addSubview:pushSourceButton];
    
    shareSourceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareSourceButton setFrame:CGRectMake(pushSourceButton.frame.size.width + pushSourceButton.frame.origin.x, shareSourceButton.frame.origin.x, pushSourceButton.frame.size.width, pushSourceButton.frame.size.height)];
    [shareSourceButton setTitle:@"共享货源" forState:UIControlStateNormal];
    [shareSourceButton setTitle:@"共享货源" forState:UIControlStateSelected];
    [shareSourceButton setTag:2];
    [shareSourceButton setTitleColor:[UIColor HexStrWithColor:@"a9a9a9"] forState:UIControlStateNormal];
    [shareSourceButton setTitleColor:[UIColor HexStrWithColor:@"ca3300"] forState:UIControlStateSelected];
    [shareSourceButton addTarget:self action:@selector(ButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [shareSourceButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    
    shareSourceLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, pushSourceButton.frame.size.height-3, pushSourceButton.frame.size.width, 3)];
    [shareSourceLabel setBackgroundColor:[UIColor clearColor]];
    [shareSourceButton addSubview:shareSourceLabel];
    [_topView addSubview:shareSourceButton];
}

/**
 *  推送货源历史货源按钮响应方法
 *
 *  @param sender
 */
- (void)ButtonAction:(UIButton *)sender
{
    UIButton *btn = sender;
    if (btn.tag == 1)
    {
        bPush = true; 
        [pushSourceLabel setBackgroundColor:[UIColor HexStrWithColor:@"cf3900"]];
        [shareSourceLabel setBackgroundColor:[UIColor clearColor]];
        [pushSourceButton setSelected:YES];
        [shareSourceButton setSelected:NO];
        [self verificationLogin];
    }
    else
    {//  共享货源
        bPush = false;
        [shareSourceLabel setBackgroundColor:[UIColor HexStrWithColor:@"cf3900"]];
        [pushSourceLabel setBackgroundColor:[UIColor clearColor]];
        [pushSourceButton setSelected:NO];
        [shareSourceButton setSelected:YES];
        [self getShareGoods];
    }
}

/**
 *  获取共享货源数据
 */
- (void)getShareGoods{
    [DataController getShareGoods:[NSNumber numberWithInt:9]
                           userId:[NSNumber numberWithInt:9]
                           lastId:[NSNumber numberWithInt:0]
                             imei:kIdentifierString
                        withBlock:^(NSDictionary *result) {
                            
                            if ([[result objectForKey:@"resCode"]isEqualToString:@"0"]) {
                                NSDictionary *data = [result objectForKey:@"data"];
                                NSArray *goodsLists = [data objectForKey:@"goodsList"];
                                [self.sourceArr removeAllObjects];
                                for (NSDictionary *dic in goodsLists) {
                                    
                                    goodsList *goods = [MTLJSONAdapter modelOfClass:[goodsList class] fromJSONDictionary:dic error:nil];
                                    [self.sourceArr addObject:goods];
                                }
                                [self.tableView reloadData];
                                return;
                                
                            } else if ([[result objectForKey:@"resCode"] isEqualToString:@"2"]){
                                // 踢掉前一个用户
                                [self getShareGoods];
                            }
                        }];
}

/**
 *  综合区域包括目的城市，出发城市以及品类，重量的信息
 */
- (void)multipeAreaView
{
    multipeView = [[UIView alloc]init];
    [multipeView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:multipeView];
    //WithFrame:CGRectMake(0, _topView.frame.size.height + _topView.frame.origin.y,kUIScreenWidth, _topView.frame.size.height)
    [multipeView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(self.view.mas_left).with.offset(-1);
         make.top.equalTo(_topView.mas_bottom);
         make.size.equalTo(_topView);
     }];

    _fromButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [multipeView addSubview:_fromButton];
    [_fromButton mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(multipeView.mas_left);
         make.centerY.equalTo(multipeView);
         make.height.equalTo(multipeView.mas_height);
         make.width.equalTo(multipeView.mas_width).with.multipliedBy(0.2);
     }];

    //float width = kUIScreenWidth/4;
    [_fromButton setTitle:@"出发地" forState:UIControlStateNormal];
    //[_fromButton setTitleEdgeInsets:UIEdgeInsetsMake(0, - width/5, 0, 0)];
    //[_fromButton setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal];
    //[_fromButton setImageEdgeInsets:UIEdgeInsetsMake(0, 4*width/5, 0, 0)];
    [_fromButton setTitleColor:[UIColor HexStrWithColor:@"a9a9a9"] forState:UIControlStateNormal];
    [_fromButton setTag:1];
    [_fromButton addTarget:self action:@selector(formCityAction:) forControlEvents:UIControlEventTouchUpInside];

    UIImageView *formImageView = [[UIImageView alloc]init];
    [formImageView setImage:[UIImage imageNamed:@"xia"]];
    [formImageView setContentMode:UIViewContentModeScaleToFill];
    [multipeView addSubview:formImageView];
    [formImageView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(_fromButton.mas_right);
         make.centerY.equalTo(multipeView);
         make.height.equalTo(multipeView.mas_height).with.multipliedBy(0.3);
         make.width.equalTo(multipeView.mas_width).multipliedBy(0.05);
     }];
    
    UIImageView *guideImageView = [[UIImageView alloc]init];
    [guideImageView setImage:[UIImage imageNamed:@"jt"]];
    [guideImageView setContentMode:UIViewContentModeScaleToFill];
    [multipeView addSubview:guideImageView];
    [guideImageView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(formImageView.mas_right).with.offset(8);
         make.centerY.equalTo(multipeView);
         make.width.equalTo(_fromButton).with.multipliedBy(0.2);
         make.height.equalTo(multipeView.mas_height).with.multipliedBy(0.30);
     }];
    
    _toButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [multipeView addSubview:_toButton];
    [_toButton mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(guideImageView.mas_right);
         make.centerY.equalTo(multipeView);
         make.size.equalTo(_fromButton);
     }];
    [_toButton setTitle:@"目的地" forState:UIControlStateNormal];
    //    [_toButton setTitleEdgeInsets:UIEdgeInsetsMake(0, - width/5, 0, 0)];
    //    [_toButton setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal];
    //    [_toButton setImageEdgeInsets:UIEdgeInsetsMake(0, 4*width/5, 0, 0)];
    [_toButton setTitleColor:[UIColor HexStrWithColor:@"a9a9a9"] forState:UIControlStateNormal];
    [_toButton setTag:2];
    [_toButton addTarget:self action:@selector(toCityAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *toImageView = [[UIImageView alloc]init];
    [toImageView setImage:[UIImage imageNamed:@"xia"]];
    [toImageView setContentMode:UIViewContentModeScaleToFill];
    [multipeView addSubview:toImageView];
    [toImageView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(_toButton.mas_right);
         make.centerY.equalTo(multipeView);
         make.height.equalTo(multipeView.mas_height).with.multipliedBy(0.25);
         make.width.equalTo(multipeView.mas_width).multipliedBy(0.05);
     }];

    _weightButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [multipeView addSubview:_weightButton];
    [_weightButton mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(toImageView.mas_right);
         make.centerY.equalTo(multipeView);
         make.height.equalTo(_fromButton);
         make.width.equalTo(_fromButton.mas_width).with.multipliedBy(1.5);
     }];
    [_weightButton setTitle:@"物品种类" forState:UIControlStateNormal];
    //    [_weightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, - width/5, 0, 0)];
    //    [_weightButton setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal];
    //    [_weightButton setImageEdgeInsets:UIEdgeInsetsMake(0, 4*width/5, 0, 0)];
    [_weightButton setTitleColor:[UIColor HexStrWithColor:@"a9a9a9"] forState:UIControlStateNormal];
    [_weightButton setTag:3];
    [_weightButton addTarget:self action:@selector(selectWeightAction:) forControlEvents:UIControlEventTouchUpInside];

    UIImageView *weightImageView = [[UIImageView alloc]init];
    [weightImageView setImage:[UIImage imageNamed:@"xia"]];
    [weightImageView setContentMode:UIViewContentModeScaleToFill];
    [multipeView addSubview:weightImageView];
    [weightImageView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(_weightButton.mas_right);
         make.centerY.equalTo(multipeView);
         make.height.equalTo(multipeView.mas_height).with.multipliedBy(0.25);
         make.width.equalTo(multipeView.mas_width).multipliedBy(0.05);
     }];
}

/**
 *  出发城市的响应方法
 *
 *  @param btn 按钮对象
 */
- (void)formCityAction:(UIButton *)btn
{
    RouteLine_ViewController *lineVC = [[RouteLine_ViewController alloc]init];
    [self.navigationController pushViewController:lineVC animated:YES];
}

/**
 *  目的城市的响应方法
 *
 *  @param btn 按钮对象
 */
- (void)toCityAction:(UIButton *)btn
{
    RouteLine_ViewController *lineVC = [[RouteLine_ViewController alloc]init];
    [self.navigationController pushViewController:lineVC animated:YES];
}

/**
 *  物品选择的方法
 *
 *  @param btn
 */
- (void)selectWeightAction:(UIButton *)btn
{
    // 使用block传值
    // 参数1：选中的物品种类
    void(^block)(NSString *name) = ^(NSString *name){
        
        [btn setTitle:name forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    };
    GoodsList_ViewController *goodsList = [[GoodsList_ViewController alloc]init];
    goodsList.sendProvince = block;
    [self.navigationController pushViewController:goodsList animated:YES];
}

/**
 *  立即抢单、取消订单点击方法
 *
 *  @param button button description
 */
- (void)grapBtnAction:(UIButton *)button{
    // 使用block传值
    // 参数1：选中的物品种类
    void(^block)(NSString *name) = ^(NSString *name){
    
        [self getShareGoods];
    };
    goodsList *goods = [self.sourceArr objectAtIndex:button.tag];
    if ([goods.goodsStatus isEqualToString:@"0"]) {
        NSMutableArray *tempArr = [NSMutableArray new];
        [DataController getLicensePlate:[NSNumber numberWithInt:9]
                                 userId:[NSNumber numberWithInt:9]
                                   imei:@"D9B99A6C-1C68-475A-AF48-B0338D8213DD"
                              withBlock:^(NSDictionary *result) {
                                  if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                      NSDictionary *data = [result objectForKey:@"data"];
                                      NSArray *licensePlateListArr = [data objectForKey:@"licensePlateList"];
                                      for (NSDictionary *dic in licensePlateListArr) {
                                          
                                          licensePlateList *licensePlate = [MTLJSONAdapter modelOfClass:[licensePlateList class] fromJSONDictionary:dic error:nil];
                                          [tempArr addObject:licensePlate];
                                      }
                                      ChooseVechileViewController *chooseVechileVC = [[ChooseVechileViewController alloc] initWithGoodsList:goods tempArr:tempArr];
                                      chooseVechileVC.sendProvince = block;
                                      [self.navigationController pushViewController:chooseVechileVC animated:YES];
                                      [self.tableView reloadData];
                                      return;
                                  } else if ([[result objectForKey:@"resCode"] isEqualToString:@"2"]){
                                      // 踢掉当前用户
                                      [self grapBtnAction:nil];
                                  }
                              }];
    } else if ([goods.goodsStatus isEqualToString:@"1"]){
        // 取消订单
        NSInteger num = [goods.goodsId integerValue];
        NSNumber * nums = @(num);
        [DataController changeOrderStatus:[NSNumber numberWithInt:5]//nums
                                    orgId:[NSNumber numberWithInt:9]
                                  orderId:[NSNumber numberWithInt:0]
                                   userId:[NSNumber numberWithInt:9]
                                  truckId:@"5"
                                     type:@"2"
                                     note:@"woxiangquxiao"
                                     imei:@"D9B99A6C-1C68-475A-AF48-B0338D8213DD"
                                withBlock:^(NSDictionary *result) {
                                    if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                        NSLog(@"取消成功");
                                        [self verificationLogin];
                                        [self getShareGoods];
                                    }else if ([[result objectForKey:@"resCode"] isEqualToString:@"2"]){
                                        [self grapBtnAction:nil];
                                    }
                                    [self.tableView reloadData];
                                }];
    }
    
}

/**
 *  拨打电话点击方法
 *
 *  @param button button description
 */
- (void)telButtonAction:(UIButton *)button{
    NSLog(@"拨打电话===%ld", button.tag);
}

/**
 *  服务评价的响应方法
 *
 *  @param sender
 */
- (void)ratingAction:(id)sender
{
    
}

/**
 *  视图的详细数据的布置区域
 */
- (void)detailView
{

    self.tableView = [[UITableView alloc]init];
    [self.view addSubview:self.tableView];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    //[tableView setScrollEnabled:YES];
    //[tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    //tableView.backgroundColor = [UIColor HexStrWithColor:@"ff0000"];
    
    //[tableView setFrame:CGRectMake(0, multipeView.frame.origin.y + multipeView.frame.size.height+9, kUIScreenWidth, kUIScreenHeight - kStateNavHeight - (multipeView.frame.origin.y + multipeView.frame.size.height+9))];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.top.equalTo(multipeView.mas_bottom);
         make.bottom.equalTo(self.view.mas_bottom);
         make.centerX.equalTo(self.view);
         make.width.mas_equalTo(kUIScreenWidth);
         
     }];
    //[tableView setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sourceArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 550;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *indentifer = @"cell_goods";
    ShipperSource_TableViewCell *cell = (ShipperSource_TableViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifer];
    if (!cell){
        cell = [[ShipperSource_TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifer];
    }
    
    goodsList *goods = [self.sourceArr objectAtIndex:indexPath.row];

    cell.customer_designationContentLabel.text = goods.pushLicensePlate;
    cell.pulicContentLabel.text = goods.releaseOrgName;
    cell.routeLabel.text = [NSString stringWithFormat:@"路线:  %@", goods.startAddressName];
    cell.categoryLabel.text = [NSString stringWithFormat:@"品类:  %@", goods.mediumType];
    cell.weightLabel.text = [NSString stringWithFormat:@"重量:  %@", goods.weight];
    cell.priceLabel.text = [NSString stringWithFormat:@"价格区间:  %@", goods.expectFreight];
    cell.deliveryDateLabel.text = [NSString stringWithFormat:@"发货日期:  %@", goods.loadGoodsTime];
    cell.publicDateLabel.text = [NSString stringWithFormat:@"发布日期:  %@", goods.releaseTime];
    cell.remarksLabel.text = [NSString stringWithFormat:@"备注:  %@", goods.note];
    cell.authenticationImageView.image = [UIImage imageNamed:@"yrz"];
    if (!bPush) {
        // 智能匹配
        UIImage *znppImage = [UIImage imageNamed:@"znpp"];
        [cell.matchingImageView setImage:znppImage];
    } else{
        cell.matchingImageView.image = [UIImage imageNamed:@""];
    }
    if ([goods.releaseOrgAuthStatus isEqualToString:@"0"]) {
    }
    
    // 立即抢单按钮
    cell.grapBtn.tag = indexPath.row;
    [cell.grapBtn addTarget:self action:@selector(grapBtnAction:) forControlEvents:UIControlEventTouchDown];
    if ([goods.goodsStatus isEqualToString:@"0"]) {
        [cell.grapBtn setTitle:@"立即抢单" forState:UIControlStateNormal];
    } else if ([goods.goodsStatus isEqualToString:@"1"]) {
        [cell.grapBtn setTitle:@"取消抢单" forState:UIControlStateNormal];
    }
    
    // 拨打电话
    cell.telBtn.tag = 100 + indexPath.row;
    [cell.telBtn addTarget:self action:@selector(telButtonAction:) forControlEvents:UIControlEventTouchDown];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    goodsList *goods = [self.sourceArr objectAtIndex:indexPath.row];
    shipgdsDetailViewController *shipgdsDetailVC = [[shipgdsDetailViewController alloc] initWithGoodsList:goods];
    [self.navigationController pushViewController:shipgdsDetailVC animated:YES];
}

/**
 *  推送货源请求
 */
- (void)verificationLogin{
    
    [DataController textRequest:[NSNumber numberWithInt:9]
                         userId:[NSNumber numberWithInt:9]
                         lastId:[NSNumber numberWithInt:0]
                           imei: @"D9B99A6C-1C68-475A-AF48-B0338D8213DD"
                      withBlock:^(NSDictionary *result) {
                          if (result) {
                              // 获取数据字典
                              id data = [result objectForKey:@"data"];
                              // 判断数据类型 如果字符串重新调用 如果字典进行解析
                              if ([[data class] isSubclassOfClass:[NSString class]]) {
                                  [self verificationLogin];
                              } else{
                                  if (data) {
                                      if ([[data allKeys] containsObject:@"goodsList"]) {
                                          NSArray *goodsLists = [data objectForKey:@"goodsList"];
                                          [self.sourceArr removeAllObjects];
                                          for (NSDictionary *dic in goodsLists) {
                                              
                                              goodsList *goos = [MTLJSONAdapter modelOfClass:[goodsList class] fromJSONDictionary:dic error:nil];
                                              [self.sourceArr addObject:goos];
                                          }
                                          [self.tableView reloadData];
                                          return;
                                      } else{
                                          NSLog(@"字典data中无值");
                                      }
                                  } else{
                                      [self verificationLogin];
                                  }
                              }
                          }
                      }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
